<template>
  <div>
    <h2>镜像管理</h2>
    <p>欢迎来到镜像管理页面！</p>
  </div>
  <div>
    <el-button type="primary" @click="$router.push('/ContainerManage')">前往容器管理</el-button>
    <el-button type="success" @click="$router.push('/settings')">前往设置</el-button>
  </div>
  <!-- <div>
    <el-button type="info" @click="showLocalImages">显示本地镜像</el-button>
  </div> -->
  <p> 本地镜像查询结果：</p>
  <el-table :data="tableDataLocalImages" stripe empty-text="">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="REPOSITORY" :label="$t('dockerimages.image.repository')" min-width= '250' show-overflow-tooltip/>
    <el-table-column prop="TAG" :label="$t('dockerimages.image.tag')" min-width= '250' show-overflow-tooltip/>
    <el-table-column prop="IMAGE_ID" :label="$t('dockerimages.image.id')" min-width= '200'show-overflow-tooltip/>
    <el-table-column prop="CREATED" :label="$t('dockerimages.image.created')" min-width= '200' show-overflow-tooltip/>
    <el-table-column prop="SIZE" :label="$t('dockerimages.image.size')" min-width= '100'show-overflow-tooltip/>
    <!-- 新增操作列 -->
  <el-table-column 
    :label="$t('dockerimages.image.actions')" 
    min-width="300"
    align="center"
  >
    <template #default="scope">
      <el-button 
        size="small"
        type="danger"
        @click="handleRemoveImage(scope.row)"
      round>
        {{ $t('dockerimages.image.delete') }}
      </el-button>
      
      <el-button 
        size="small" 
        type="primary"
        :disabled="getExportProgress(scope.row) > 0"
        @click="handleExportImage(scope.row)"
      round>
        {{ $t('dockerimages.image.export') }}
      </el-button>
      <!-- <el-progress 
        type="circle" 
        :width='30' 
        v-else
        :percentage="getExportProgress(scope.row)"
        :status="getExportProgress(scope.row) === 100 ? 'success' : ''"/> -->
      <el-button 
        size="small" 
        type="primary" 
        @click="handleShowImageDetails(scope.row)"
      round>
        {{ $t('dockerimages.image.details') }}
      </el-button>
      <el-dropdown trigger="click" size="small" style="margin-left: 10px;">
        <el-button type="primary" size="small" round>更多 <el-icon class="el-icon--right"><arrow-down /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item :icon="Plus">Action 1</el-dropdown-item>
            <el-dropdown-item :icon="CirclePlusFilled">Action 2</el-dropdown-item>
            <el-dropdown-item :icon="CirclePlus">Action 3</el-dropdown-item>
            <el-dropdown-item :icon="Check">Action 4</el-dropdown-item>
            <el-dropdown-item :icon="CircleCheck">Action 5</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-progress 
      v-show="getExportProgress(scope.row) > 0"
      :percentage="getExportProgress(scope.row)"
      :format="format"
      :text-inside="true"
      :stroke-width="20"
      :status="getExportProgress(scope.row) === 100 ? 'success' : '' "
      striped 
      striped-flow
      :duration="5"/>
    </template>
  </el-table-column>
  </el-table>
  <el-pagination 
    background 
    layout="prev, pager, next"  
    :page-size="pageSize" 
    :total=images.length
    style="margin-top: 20px;"
    v-model:current-page="currentPage"
    />
</template>

<script setup lang="ts">
import { onMounted, ref, computed, watch, type ComputedRef} from 'vue'
// import type { TableInstance } from 'element-plus'
import { ElMessage, ElMessageBox, SCOPE } from 'element-plus'
import { useDockerImagesStore } from '@/stores/dockerImages'
import { storeToRefs } from 'pinia'
import {
  ArrowDown,
  Check,
  CircleCheck,
  CirclePlus,
  CirclePlusFilled,
  Plus,
} from '@element-plus/icons-vue'

// const tableLayout = ref<TableInstance['tableLayout']>('fixed')

const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(1000)

const dockerStore = useDockerImagesStore()

const { images } = storeToRefs(dockerStore)

// 用 Map 存储每个镜像的进度
const exportProgressMap = ref<Record<string, number>>({});
const exportImageException = ref(0)

const format = (percentage: number) => (percentage === 1 ? 'loading' : `${percentage}%`)

function getExportProgress(image: any): number {
  return exportProgressMap.value[getImageKey(image)] || 0
}

function getImageKey(image: any): string {
  return `${image.IMAGE_ID}_${image.TAG}`
}

async function handleExportImage(image: any) {
  console.log(`点击了${image.REPOSITORY}的export按钮`);
  const imageKey = getImageKey(image);
  exportProgressMap.value[imageKey] = 1;
  const response = await fetch(`/api/docker/images/${image.IMAGE_ID}/export`);
  console.log('Response status:', response.status);
  console.log('Response body:', response.body);
 
  if (!response.ok) {
      console.error('导出失败:', response.status);
      exportProgressMap.value[imageKey] = 0;
      exportImageException.value = 1
      return;
  }

  const reader = response.body?.getReader();
  if (!reader) {
    console.error('导出失败: response.body 为空');
    exportProgressMap.value[imageKey] = 0;
    exportImageException.value = 1
    return;
  }
  
  const contentLength = +(response.headers.get('Content-Length') || 0);
  console.log("contentLengh = " + contentLength);
  let receivedLength = 0;
  const chunks: Uint8Array[] = [];

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    chunks.push(value);
    receivedLength += value.length;

    if (contentLength) {
      exportProgressMap.value[imageKey] = Math.floor((receivedLength / contentLength) * 100);
      console.log("exportProgress value = " + exportProgressMap.value[imageKey])
    }
  }

  const blob = new Blob(chunks as BlobPart[], { type: 'application/gzip' });
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = `${image.REPOSITORY}_${image.TAG}.tar.gz`;
  link.click();
  
  // 延迟重置，恢复按钮显示
  setTimeout(() => {
    exportProgressMap.value[imageKey] = 0;
  }, 3000);

}


// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(images.value.length / pageSize.value)
})

// 计算当前页显示的数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return images.value.slice(start, end)
})

// 监听数据变化，重置到第一页
watch(images, () => {
  currentPage.value = 1
}, { deep: true })

// 页面加载时自动获取镜像列表
onMounted(() => {
  const imagesIsEmpty: ComputedRef<boolean> = computed(() => dockerStore.images.length === 0)
  console.log("镜像列表是否为空：", imagesIsEmpty.value)
  if (imagesIsEmpty.value == true) {
    console.log("镜像列表为空，正在获取镜像列表...")
    showLocalImages()
    console.log("获取镜像列表完成。")
  }
  
})
// 计算属性转换数据格式
const tableDataLocalImages = computed(() => {
  return currentPageData.value.map(img => ({
    REPOSITORY: img.REPOSITORY || img.name || '<none>',
    TAG: img.TAG || '<none>',
    IMAGE_ID: formatImageID(img.IMAGE_ID),
    CREATED: formatUTCTime(img.CREATED),
    SIZE: formatSize(img.SIZE)
  }))
})


// 点击按钮获取镜像列表
const showLocalImages = async () => {
  // 检查网络连接
  if (!window.navigator.onLine) {
    ElMessage.error('网络不可用，请检查您的连接。')
    return;
  }

  try {
    const success = await dockerStore.fetchImages()
    if (success) {
        ElMessage.success('获取镜像成功')
    } else {
        ElMessage.error('获取镜像失败: ' + (dockerStore.error || '未知错误'))
    }
    
  } catch (error) {
    ElMessage.error('获取镜像失败: ' + (error as Error).message)
  }
}

// 删除镜像
const handleRemoveImage = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该镜像吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await dockerStore.removeImage(row.IMAGE_ID)
    ElMessage.success('镜像删除成功')
    showLocalImages() // 刷新镜像列表
  } catch (error) {
    if ((error as Error).message !== 'cancel') {
      ElMessage.error('删除失败: ' + (error as Error).message)
    }
  }
}

// 导出镜像
// const handleExportImage = async (row: any) => {
//   try {
//     // Placeholder for export logic
//     console.log('Export image action triggered for', row)
//     ElMessage.success('镜像导出功能待实现')
//   } catch (error) {
//     ElMessage.error('导出失败: ' + (error as Error).message)
//   }
// }

// 显示镜像详情
const handleShowImageDetails = async (row: any) => {
  try {
    // Placeholder for showing details logic
    console.log('Show image details action triggered for', row)
    ElMessage.success('镜像详情功能待实现')
  } catch (error) {
    ElMessage.error('显示详情失败: ' + (error as Error).message)
  }
}
// 辅助函数：格式化日期
const formatDate = (timestamp: number) => {
  // 检查时间戳单位并自动转换
  let actualTimestamp = timestamp;
  
  // 如果时间戳是10位数（秒级），转换为毫秒
  if (timestamp.toString().length === 10) {
    actualTimestamp = timestamp * 1000;
  }
  // 如果时间戳是13位数（毫秒级），直接使用
  else if (timestamp.toString().length === 13) {
    actualTimestamp = timestamp;
  }
  // 其他情况可能需要特殊处理
  else {
    console.warn('时间戳格式异常，请检查输入值:', timestamp);
  }
  
  const date = new Date(actualTimestamp);
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 辅助函数：格式化大小
const formatSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1000
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatImageID = (Imageid: string) => {
  return Imageid.slice(7, 19)
}

const formatUTCTime = (utcTimeString: string) => {
  const localTime = new Date(utcTimeString).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
  // console.log('UTC Time:', utcTimeString);
  // console.log('Local Time:', localTime);
  return localTime;
}
</script>